import { createStore } from "../vuex";
// 数据持久化插件
function customPlugin(store) {
  const localState = localStorage.getItem("VUEX:STATE");
  if(localState){
    store.replaceState(JSON.parse(localState));
  }
  // 调用mutation时就会执行此回调
  store.subscribe((mutation, state) => {
    // mutation里有方法名和payload
    localStorage.setItem("VUEX:STATE", JSON.stringify(state));
  })
}
const store = createStore({
  // 会按照注册顺序执行插件,并把store当成参数
  plugins: [
    customPlugin,
  ],
  // 开启严格模式，不允许用户在mutations外修改数据，否则就报错
  strict: true,
  state: {
    a: 1,
  },
  getters: {
    double(state) {
      return state.a * 2;
    }
  },
  mutations: {
    add(state, payload) {
      state.a += payload;
    }
  },
  actions: {
    asyncAdd({ commit, state, dispatch }, value) {
      return new Promise(res => {
        setTimeout(() => {
          commit("add", value);
          res()
        }, 1000);
      })
    },
  },
  modules: {
    bCount: {
      namespaced: true,
      state: {
        b: 2,
      },
      mutations: {
        add(state) {
          state.b += 2;
        }
      },
      modules: {
        dCount: {
          namespaced: true,
          state: {
            d: 3,
          },
          mutations: {
            add(state) {
              state.d += 3;
            }
          },
        }
      }
    },
    cCount: {
      state: {
        c: 4,
      },
      mutations: {
        add(state) {
          state.c += 4;
        }
      },
      modules: {
        eCount: {
          namespaced: true,
          state: {
            e: 5,
          },
          mutations: {
            add(state) {
              state.e += 5;
            }
          },
        }
      }
    }
  }
});

store.registerModule(['bCount', "zCount"], {
  namespaced: true,
  state: {
    z: 10,
  },
  mutations: {
    add(state) {
      state.z += 10;
    }
  },
})
console.log(store)
export default store;